<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>video</title>
</head>

<body>
<div>
    <video id="localVideo" class="video" autoplay="autoplay"></video>
    <video id="remoteVideo" class="video" autoplay="autoplay"></video>
    <p style="color: red;">WebRTC会话，请保持该页面打开!</p>
</div>
</body>
</html>
<script src="./adapter-latest.js"></script>
<script>
    const localVideo = document.querySelector('#localVideo');
    const remoteVideo = document.querySelector('#remoteVideo');

    const config = {
        iceServers: [
            { urls: 'turn:www.2edge.cn:3874','username': 'jiexun', 'credential': 'jiexun' }
        ],
    };

    let peerConnection;

    let socket, userId, toUserId;
    let constraints = {
        video: false,
        audio: false
    }
    userId = 8888
    webSocketUrl = (location.protocol == "https:" ? "wss:" : "ws:") + '//client.2edge.cn/aiclient/webRTC/';

    // 本地流和远端流
    let localStream, remoteStream;

    //websocket连接
    function startWebsocket() {
        //请求服务获取设备id
        fetch("/index/test",
                {
                method:"POST",
                body: JSON.stringify({"e":"e"}),
                headers: {
                    'Content-Type': 'application/json',
                }
        }).then((response) => {
            return response.json()
        }).then((data) => {
            console.log(data)
            if(data){
                userId = data.data
                socket = new WebSocket(webSocketUrl + userId);
                //连接成功
                socket.onopen = function (e) {
                    console.log('连接服务器成功!')
                };
                //server端请求关闭
                socket.onclose = function (e) {
                    console.log('close')
                    socket = null
                };
                //error
                socket.onerror = function (e) {
                    console.error(e)
                    socket = null
                };
                socket.onmessage = onmessage
            }
        })
    }
    //连接服务器
    startWebsocket();

    //开启本地的媒体设备
    async function startHandle() {
        // 1.获取本地音视频流
        // 调用 getUserMedia API 获取音视频流
        await navigator.mediaDevices.enumerateDevices()
            .then((devices)=> {
                devices.forEach((device)=>{
                    if("audioinput" == device.kind){
                        console.log('audio true')
                        constraints.audio = {
                            // 设置回音消除
                            noiseSuppression: true,
                            // 设置降噪
                            echoCancellation: true,
                        }
                    }
                    else if("videoinput" == device.kind){
                        console.log('video true')
                        constraints.video = true
                    }
                });
            })
            .catch(function(err) {
                console.log(err.name + ": " + err.message);
            });

        console.log(constraints)
        await navigator.mediaDevices.getUserMedia(constraints)
            .then(gotLocalMediaStream)
            .catch((err) => {
                console.log('getUserMedia 错误', err);
                //创建点对点连接对象
            });

        createConnection();
    }

    function gotLocalMediaStream(mediaStream) {
        // getUserMedia 获得流后，将音视频流展示并保存到 localStream
        localVideo.srcObject = mediaStream;
        localStream = mediaStream;
    }

    function onmessage(e) {

        const json = JSON.parse(e.data)
        const description = json.message
        toUserId = json.userId

        switch (description.type) {
            case 'connect':
                //初始化打开设备准备连接
                startHandle().then(() => {
                    createOffer()
                })
                break;
            case 'offer':
                peerConnection.setRemoteDescription(new RTCSessionDescription(description)).then(() => {
                    peerConnection.createAnswer().then(function (answer) {
                        peerConnection.setLocalDescription(answer).then(() => {
                            console.log('设置本地answer成功!');
                            socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': answer }));
                        }).catch((err) => {
                            console.error('设置本地answer失败', err);
                        });
                    }).catch(e => {
                        console.error(e)
                    });
                }).catch((err) => {
                    console.log('local 设置远端描述信息错误', err);
                });
                break;
            case 'icecandidate':
                // 创建 RTCIceCandidate 对象
                let newIceCandidate = new RTCIceCandidate(description.icecandidate);

                // 将本地获得的 Candidate 添加到远端的 RTCPeerConnection 对象中
                peerConnection.addIceCandidate(newIceCandidate).then(() => {
                    console.log(`addIceCandidate 成功`);
                }).catch((error) => {
                    console.log(`addIceCandidate 错误:\n` + `${error.toString()}.`);
                });
                break;
            case 'answer':
                peerConnection.setRemoteDescription(new RTCSessionDescription(description)).then(() => {
                    console.log('设置remote answer成功!');
                }).catch((err) => {
                    console.log('设置remote answer错误', err);
                });
                break;
            case 'stop':
                hangupHandle()
                break;
            case 'close':
                closeCurrentWindow()
                break;
            default:
                break;
        }
    }

    /**
     * 创建peerConnection连接对象
     */
    function createConnection() {
        peerConnection = new RTCPeerConnection(config)

        //添加媒体轨
        if (localStream) {
            localStream.getTracks().forEach((track) => {
                peerConnection.addTrack(track, localStream)
            })
        }

        // 监听返回的 Candidate
        peerConnection.addEventListener('icecandidate', handleConnection);
        // 监听 ICE 状态变化
        peerConnection.addEventListener('iceconnectionstatechange', handleConnectionChange)
        //拿到流的时候调用
        peerConnection.addEventListener('track', gotRemoteMediaStream);
    }

    /**
     * 创建发起方会话描述对象（createOffer），设置本地SDP（setLocalDescription），
     * 并通过信令服务器发送到对等端，以启动与远程对等端的新WebRTC连接。
     */
    function createOffer() {
        // 发送offer
        peerConnection.createOffer().then(description => {
            console.log(`本地创建offer返回的sdp:\n${description.sdp}`)

            // 将 offer 保存到本地
            peerConnection.setLocalDescription(description).then(() => {
                console.log('local 设置本地描述信息成功');
                // 本地设置描述并将它发送给远端
                socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': description }));
            }).catch((err) => {
                console.log('local 设置本地描述信息错误', err)
            });
        })
            .catch((err) => {
                console.log('createdOffer 错误', err);
            });
    }

    function hangupHandle() {
        // 关闭连接并设置为空
        if(peerConnection){
            peerConnection.close();
            peerConnection = null;
        }

        if(localStream){
            localStream.getTracks().forEach((track) => {
                track.stop()
            })
        }
    }

    // 3.端与端建立连接
    function handleConnection(event) {
        // 获取到触发 icecandidate 事件的 RTCPeerConnection 对象
        // 获取到具体的Candidate
        console.log("handleConnection")
        const icecandidate = event.candidate;

        if (icecandidate) {
            socket.send(JSON.stringify({
                'userId': userId,
                'toUserId': toUserId,
                'message': {
                    type: 'icecandidate',
                    icecandidate: icecandidate
                }
            }));
        }
    }

    // 4.显示远端媒体流
    function gotRemoteMediaStream(event) {
        console.log('remote 开始接受远端流')

        if (event.streams[0]) {
            remoteVideo.srcObject = event.streams[0];
            remoteStream = event.streams[0];
        }
    }

    function handleConnectionChange(event) {
        const pc = event.target;
        console.log('ICE state change event: ', event);
        console.log(`ICE state: ` + `${pc.iceConnectionState}.`);
        if (pc.iceConnectionState === "failed" || pc.iceConnectionState === "disconnected" || pc.iceConnectionState === "closed") {
            // Handle the failure
            hangupHandle()
        }
    }


    const interval = setInterval(() => {
        if(!socket || socket.readyState != socket.OPEN){
            console.log("重新连接...............")
            startWebsocket();
        }else {
            socket.send(JSON.stringify({
                'toUserId': '',
                'heart': true
            }));
        }
    },30000)

    function closeCurrentWindow() {
        hangupHandle()

        if(interval){
            clearInterval(interval)
        }
        if(socket && socket.readyState == socket.OPEN) {
            socket.close()
        }
        console.debug("close window")
        window.opener=null;
        window.open('','_self');
        window.close();
    }
</script>
<style>
    .video {
        background-color: black;
        height: 30vh;
    }
</style>